package com.example.sunny.view.weather

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.example.sunny.R
import com.example.sunny.pojo.weather.DailyResponse
import com.example.sunny.pojo.weather.getSky
import com.example.sunny.utils.UIUtils
import com.github.mikephil.charting.components.Description
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.ValueFormatter
import com.google.android.material.card.MaterialCardView
import kotlinx.android.synthetic.main.fragment_daily_weather.*
import pl.droidsonroids.gif.GifImageView
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class DailyWeatherFragment():Fragment() {

    lateinit var gifImageView: GifImageView
    lateinit var dailySkycon:TextView
    lateinit var dailyTemperature: TextView
    lateinit var daily:DailyResponse.Daily

    lateinit var dailyLifeIndex:View
    var position:Int = 0
    var isCentigrade:Boolean = true


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_daily_weather,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        gifImageView = view.findViewById<GifImageView>(R.id.gifImageView)
        dailySkycon = view.findViewById<TextView>(R.id.dailySkycon)
        dailyTemperature = view.findViewById<TextView>(R.id.dailyTemperature)
        //通过intent得到daily和position
        daily = arguments?.getParcelable<DailyResponse.Daily>("daily")!!
        position = arguments?.getInt("position",0)!!
        isCentigrade = arguments?.getBoolean("is_centigrade")!!

        val sky = getSky(daily.skycon[position].value)
        gifImageView.setImageResource(sky.gif)
        dailySkycon.text = sky.info
        dailyTemperature.text = daily.temperature[position].run {
            if (isCentigrade){
                "${min.toInt()}~${max.toInt()} ℃"
            }else{
                "${(min*33.8f).toInt()}~${(max*33.8f).toInt()} ℉"
            }
        }

        dailyLifeIndex = view.findViewById<View>(R.id.dailyLifeIndex)
        UIUtils.InflateUI.inflateLifeIndex(dailyLifeIndex,daily,position)
        view.setBackgroundResource(sky.bg)

        //绘制曲线
        drawLine(daily)
        //绘制曲线x轴label
        val icons = ArrayList<Int>()
        val descs = ArrayList<String>()
        for (skycon in daily.skycon) {
            icons.add(getSky(skycon.value).icon)
            descs.add(getSky(skycon.value).info)
        }
        for (i in icons.indices) {
            val v = LayoutInflater.from(activity).inflate(R.layout.skycon_icon, weatherIconLyout, false)
            val imageView = v.findViewById<ImageView>(R.id.skycon_icon)
            val textView = v.findViewById<TextView>(R.id.skycon_desc)
            v as MaterialCardView
            if (i==position){
                v.setCardBackgroundColor(resources.getColor(R.color.semiTransparentColor))
            }
            imageView.setImageResource(icons[i])
            textView.text = descs[i]
            weatherIconLyout.addView(v)
        }
        Log.d("icon.size",icons.size.toString())
    }

    private fun drawLine(daily:DailyResponse.Daily){
        val dates = ArrayList<String>()
        val simpleDateFormat = SimpleDateFormat("MM-dd", Locale.getDefault())

        for (skycon in daily.skycon) {
            dates.add(simpleDateFormat.format(skycon.date))
        }

        val maxEntries = ArrayList<Entry>()
        val minEntries = ArrayList<Entry>()

        val temperature = daily.temperature

        Log.d("temperature.size",temperature.size.toString())
        for (i in temperature.indices) {
            maxEntries.add(Entry(i.toFloat(),temperature[i].max))
            minEntries.add(Entry(i.toFloat(),temperature[i].min))
        }
        val maxLineDataSet = LineDataSet(maxEntries,"温度")
        val minLineDataSet = LineDataSet(minEntries,"温度")
        val lineData = LineData(maxLineDataSet, minLineDataSet)
        val description = Description()
        description.isEnabled = false

        lineChart.apply {
            data = lineData
            //不显示边框
            setDrawBorders(false)
            //沿x轴开启动画
//            animateX(3000)
            //不显示description
            this.description = description
            //不显示y轴
            axisLeft.isEnabled = false
            axisRight.isEnabled = false
            //不显示图例
            legend.isEnabled = false
            //设置不可拖拽，移动，放缩等
            isDragEnabled =false
            isDragDecelerationEnabled = false
            setTouchEnabled(false)
//            setXAxisRenderer(CustomXAxisRenderer(viewPortHandler,xAxis,Transformer(viewPortHandler),icons))
            extraTopOffset = 2 * 12f
        }

        //设置x轴
        lineChart.xAxis.apply {
            //设置范围
            axisMinimum = 0f
            mAxisMaximum = 150f
            granularity = 1f
            //设置横坐标标签
            Log.d("dates",dates.toString())
            valueFormatter = object : ValueFormatter(){
                override fun getFormattedValue(value: Float): String {
                    return dates[value.toInt()]
                }
            }
            setDrawGridLines(false)
            setDrawAxisLine(false)
            labelCount = 15
            textColor = Color.WHITE
            textSize = 12f
            setDrawLabels(true)
            Log.d("lineChart",xOffset.toString())

        }
        maxLineDataSet.setStyle()
        minLineDataSet.setStyle()

    }

    private fun LineDataSet.setStyle(){
        //实心
        setDrawCircleHole(false)
        //圆圈颜色
        setCircleColor(Color.WHITE)
        //文字大小、颜色
        valueTextSize = 12f
        valueTextColor = Color.WHITE
        //散点连接方式（折线）
        mode = LineDataSet.Mode.LINEAR
        //线条颜色
        color = Color.WHITE
        //线条宽度
        lineWidth = 3.5f
        valueFormatter = object : ValueFormatter(){
            override fun getFormattedValue(value: Float): String {
                return if (isCentigrade) {
                    "${value.toInt()}℃"
                } else {
                    "${(value * 33.8f).toInt()} ℉"
                }
            }
        }
    }

}